package model.element;

import java.awt.Color;
import java.util.LinkedList;
import java.util.Random;

import javax.swing.JLayeredPane;

import model.Element;
import model.World;
import utility.pathfinding.DepthFirstSearch;
import utility.pathfinding.Pathfinding;

public class Unit extends Element {
	public static final int UNIT_SIZE = 20;
	
	private Color color = Color.blue;
	private Road location;
	private LinkedList<Road> path = null;
	
	private int speed = 1;
	
	public Unit(int x, int y, int width, int height, Road location) {
		super(x, y, width, height, false);
		this.location = location;
	}
	public Unit(int x, int y, int width, int height) {
		this(x, y, width, height, null);
	}
	@Override
	public void kill() {
		alive = false;
	}

	@Override
	public void tick() {
		
		if(path!=null){
			int x = 0;
			int y = 0;
			if(location==path.peekFirst()){
				path.removeFirst();
			}
			if(path.isEmpty()){
				path = null;
			}else{
				Road next = path.peekFirst();
				int dx = next.getX()+next.getWidth()/2;
				int dy = next.getY()+next.getHeight()/2;
				if(dx>getX()){
					x+=speed;
				}else if(dx<getX()){
					x-=speed;
				}
				if(dy>getY()){
					y+=speed;
				}else if(dy<getY()){
					y-=speed;
				}
				move(x, y);
				if(next.getRectangle().contains(getX(), getY())){
					location = next;
				}
			}
		}
		
	}
	
	public synchronized void search(Road goal, World world){
		//path = (new DepthFirstSearch()).depthFirst(location, goal, world);
		//path = Pathfinding.depthFirst(location, goal, world);
		path = Pathfinding.anotherDFS(location, goal);
		//path = Pathfinding.depthFirst(location, goal, world);
		if(path != null && path.isEmpty()){
			System.out.println("Path is EMPTY!");
			path = null;
		}
	}

	@Override
	public boolean blocks(Element e) {
		return false;
	}

	public boolean interactable(){
		return false;
	}
	
	public Color getColor(){
		return color;
	}
	
	public void setColor(Color c){
		this.color = c;
	}
	
	@Override
	public int depth() {
		return JLayeredPane.DEFAULT_LAYER;
	}
	public synchronized boolean hasPath() {
		return path!=null&&!path.isEmpty();
	}

	
}
